package com.adaxi.adc.business.vehicletrip.websocket;

import com.adaxi.adc.business.vehicletrip.pojo.Response;
import com.adaxi.adc.business.vehicletrip.service.VehicleTripService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;


@Component
@ServerEndpoint("/websocket-vehicletrip/{userId}")
public class WebSocketServer {
    // 注入 VehicleTripService
    private static VehicleTripService vehicleTripService;
    private static RocketMQTemplate rocketMQTemplate;
    private static final CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<>();
    private static final ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private Session session;
    private String userId;

    // 当Spring容器创建WebSocketServer Bean时，将RocketMQTemplate注入，然后赋值给rocketMQTemplate
    @Autowired
    public void setRocketMQTemplate(RocketMQTemplate rocketMQTemplate) {
        WebSocketServer.rocketMQTemplate = rocketMQTemplate;
    }

    // 同样的方式注入VehicleTripService
    @Autowired
    public void setVehicleTripService(VehicleTripService vehicleTripService) {
        WebSocketServer.vehicleTripService = vehicleTripService;
    }

    private void handleResponse(String jsonMessage) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            // 将 JSON 字符串解析为 Java 对象
            Response response = objectMapper.readValue(jsonMessage, Response.class);

            String destination = "response-topic";

            // 如果消息是 "同意接单"，则增加乘客数量
            if ("同意接单".equals(response.getMessage())) {
                vehicleTripService.increasePassengers(response.getTripId(), response.getPassengers());
            }

            // 将消息发送到消息队列
            rocketMQTemplate.syncSend(destination, jsonMessage);
            logger.info("回复消息已发送: " + jsonMessage);
        } catch (Exception e) {
            logger.error("处理响应消息出错： " + jsonMessage, e);
        }
    }

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "userId") String userId) {
        this.session = session;
        this.userId = userId;
        webSockets.add(this);
        sessionPool.put(userId, session);
        logger.info("【WebSocket 消息】有新的连接，总数为:" + webSockets.size());
        logger.info("当前建立连接的用户id是" + userId);
    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);
        sessionPool.remove(this.userId);
        logger.info("【WebSocket 消息】连接断开，总数为:" + webSockets.size());
    }

    @OnMessage
    public void onMessage(String message) {
        logger.info("【WebSocket 消息】收到客户端消息:" + message);
        handleResponse(message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("用户错误,原因:" + error.getMessage());
        error.printStackTrace();
    }

    public void sendAllMessage(String message) {
        logger.info("【websocket消息】广播消息:" + message);
        for (WebSocketServer webSocket : webSockets) {
            try {
                if (webSocket.session.isOpen()) {
                    webSocket.session.getAsyncRemote()
                                     .sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendOneMessage(String userId, String message) {
        Session session = sessionPool.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.getAsyncRemote()
                       .sendText(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void sendMoreMessage(String[] userIds, String message) {
        for (String userId : userIds) {
            Session session = sessionPool.get(userId);
            if (session != null && session.isOpen()) {
                try {
                    logger.info("【websocket消息】 单点消息:" + message);
                    session.getAsyncRemote()
                           .sendText(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
